package com.lin.manager.common.utils;

import java.util.Map;
import java.util.Objects;

/**
 * @作者: 林江
 * @创建时间: 2024/8/22
 * @功能:
 */
public class StrTemplateParser {

    private String open = "${";
    private String close = "}";
    Map<String, Object> templateParam;

    public StrTemplateParser(Map<String, Object> templateParam) {
        this.templateParam = templateParam;
    }

    public StrTemplateParser(String open, String close, Map<String, Object> templateParam) {
        this.open = open;
        this.close = close;
        this.templateParam = templateParam;
    }

    /**
     * 格式化的内容 - 模仿mybatis解析sql表达式
     * 您的验证码${code}，该验证码${minute}分钟内有效，请勿泄露给他人！
     *
     * @return
     */
    public String parse(String text) {
        if (Objects.isNull(text) || text.isEmpty()) {
            return text;
        }

        // 搜索 "${" 字符串
        int start = text.indexOf(open);
        if (start == -1) {
            return text;
        }

        // 将字符串变为字符数组形式
        char[] src = text.toCharArray();

        int offset = 0;
        final StringBuilder builder = new StringBuilder();
        StringBuilder expression = null;
        do {
            if (expression == null) {
                expression = new StringBuilder();
            } else {
                // 多次循环遍历的时候，表达式只会有一个值。
                expression.setLength(0);
            }

            builder.append(src, offset, start - offset);
            offset = start + open.length();

            // 字符串将从 offset 偏移量开始，搜索 ”}“ 字符串
            int end = text.indexOf(close, offset);
            while (end > -1) {
                if (end > offset) {
                    expression.append(src, offset, end - offset);
                    offset = end + close.length();
                } else {
                    break;
                }
            }

            // 解析出口
            if (end == -1) {
                builder.append(src, start, src.length - start);
                offset = src.length;
            } else {
                // 将表达式 替换成 数据
                builder.append(templateParam.get(expression.toString()));
                offset = end + close.length();
            }

            start = text.indexOf(open, offset);
        } while (start > -1);
        if (offset < src.length) {
            builder.append(src, offset, src.length - offset);
        }
        return builder.toString();
    }

}